package com.project.Main;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.project.Library.Connect;
import com.project.trac.R;

public class TestQueries extends ListActivity {
	
	Connect cf = new Connect();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.testqueries);
		
		cf.setRemoteIP("192.168.20.2");
		cf.setRemotePort(3306);
		cf.setRemoteDB("db_thesis");
		
		cf.setRemoteDIR("file-upload");
		
		/* Debugging Messages: check for jdbc connection */
		//System.out.println("-------------- getRemoteURL()");
		//System.out.println(cf.getRemoteURL());
		
		// Execute background AsyncTask
		new LoadInBackground().execute();

		/* Android UI Objects */
		// Get List View to disable onClick events
//		final ListView lv = getListView();
		
		View view = ListView.inflate(getApplicationContext(), R.layout.testqueries_detail, null);
		view.setFocusable(false);
		view.setFocusableInTouchMode(false);
		view.setClickable(true);
		view.setEnabled(true);
		
		Button download = (Button) view.findViewById(R.id.download);
		download.setOnClickListener(new OnClickListener() {
			
			int ctr = 0;
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				ctr++;
				System.out.println(ctr);
			}
		});
		
	}

	/*
	 * Background AsyncTask to load database items into the list using JDBC connections
	 */
	class LoadInBackground extends AsyncTask<String, String, String> {

		// Data and Collection Parameters : HashMap and ArrayList
		HashMap<String, String> m = new HashMap<String, String>();
		ArrayList<HashMap<String, String>> classRecord = new ArrayList<HashMap<String, String>>();

		// Android UI Objects
		ProgressDialog dialog;
		ListAdapter adapter;

		// HashMap KEYS and Values cannot be null!
		String KEY_DOC_NAME = " ";
		String KEY_DOC_PATH = " ";

		String VALUE_DOC_NAME = " ";
		String VALUE_DOC_PATH = " ";
		
		Connection conn;
		ResultSet rs;
		Statement stmt;
		PreparedStatement pstmt;

		protected void onPreExecute() {
			super.onPreExecute();
			/* Debugging Messages */
			// System.out.println("------------------ onPreExecute call");

			dialog = new ProgressDialog(TestQueries.this);
			dialog.setMessage("Retrieving the file list, please wait.");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.show();

		}

		protected String doInBackground(String... args) {
			
			/* Debugging Messages */
			//System.out.println("------------------ doInBackground call");

			try {
				if (conn == null) {
					/* Debugging Messages */
					System.out.println("Connection is " + conn + "!\nOpening new connection!");
					
					 Class.forName(cf.getDriverClass()).newInstance();
			            cf.setConn((Connection) DriverManager.getConnection(cf.getRemoteURL(), cf.getUsername(), cf.getPassword()));
			            cf.setStmt(cf.getConn().createStatement());
			            
			            rs = cf.getStmt().executeQuery("SELECT doc_name, doc_path FROM documents");

			        /* Debugging Messages : check if RS is empty */
					//System.out.println("RS ---------------: " + rs);
					
					/* Debugging Messages */
					System.out.println("Now connected to database!");
					
					while (rs.next()) {
//						
//						// Retrieving database items using its column name
//						// Storing each database item (value) in key
						VALUE_DOC_NAME = rs.getString("doc_name");
						
						// creating a new HashMap to store
						// each new value retrieved from database
						m = new HashMap<String, String>();
						
						// adding each child node to HashMap key => value
						m.put(KEY_DOC_NAME, rs.getString("doc_name"));
						
						// adding HashMap to ArrayList
						classRecord.add(m);
						
						/* Debugging Messages : print check for HashMap values */
						//System.out.println(m.values());
						
					}

				} else {
					// TODO when con != null
					/* Debugging Messages */
					// System.out.println("Connection is still open!");
				}
			} catch (SQLException e) {
				System.out.println("doInBackground: ** SQLException ** ");
				System.err.println(e);
			} catch (InstantiationException e) {
				System.out.println("doInBackground: ** Instantiation Exception ** ");
				System.err.println(e);
			} catch (IllegalAccessException e) {
				System.out.println("doInBackground: ** Illegal Access Exception ** ");
				System.err.println(e);
			} catch (ClassNotFoundException e) {
				System.out.println("doInBackground: ** Class Not Found Exception ** ");
				System.err.println(e);
			} finally {
				try {
					cf.getConn().close();
				} catch (SQLException e) {
					System.out.println("doInBackground/finally: ** SQLException ** ");
					System.err.println(e);
				}
			}
			
			return null;
		}

	
		protected void onPostExecute(String postExecute) {
			/** Debugging Messages */
			System.out.println("------------------ onPostExecute call");

			// dismiss dialog after getting table elements
			dialog.dismiss();

			// update Android UI from background thread
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					// update data into ListView
					adapter = new SimpleAdapter(TestQueries.this, classRecord,
							R.layout.testqueries_detail, 
							new String[] { KEY_DOC_NAME, VALUE_DOC_NAME }, 
							new int[] {	R.id.name_actual, R.id.number_actual });

					// updating ListView
					setListAdapter(adapter);

				}

			});

		}

	} // end sub-class Connect

}